package com.bckj.fastboot.core.extra.dbsearch.servlet;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bckj.fastboot.core.extra.easyexcel.EasyExcelUtils;
import com.bckj.fastboot.core.jackson.JsonUtils;
import com.bckj.fastboot.core.lang.model.ApiResponse;
import com.bckj.fastboot.core.extra.dbsearch.DbSearcher;
import com.bckj.fastboot.core.extra.dbsearch.dbview.DbView;
import com.bckj.fastboot.core.extra.dbsearch.dbview.DbViewFactory;
import com.bckj.fastboot.core.extra.dbsearch.model.DbSearchRequest;
import com.bckj.fastboot.core.page.PageSupport;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
public class DbSearchServlet extends HttpServlet {

    private final DbSearcher dbSearcher;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestURI = req.getRequestURI();
        if (requestURI.endsWith("download")) {
            doDownload(req, resp);
            return;
        }
        doSearch(req, resp);
    }

    /**
     * 查询
     */
    private void doSearch(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String viewId = req.getParameter("viewId");
        try {
            String jsonStr = req.getReader().lines().collect(Collectors.joining());
            DbSearchRequest request = JsonUtils.toBean(jsonStr, DbSearchRequest.class);
            DbView view = DbViewFactory.getDbView(viewId);
            IPage<?> page = PageSupport.page(() -> dbSearcher.search(view, request, view.getType()));
            resp.getWriter().write(JsonUtils.toJsonStr(ApiResponse.ok(page)));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            resp.getWriter().write(JsonUtils.toJsonStr(ApiResponse.failed(e.getMessage())));
        }
    }

    /**
     * 下载
     */
    private void doDownload(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String viewId = req.getParameter("viewId");
        try {
            String jsonStr = req.getReader().lines().collect(Collectors.joining());
            DbSearchRequest request = JsonUtils.toBean(jsonStr, DbSearchRequest.class);
            DbView view = DbViewFactory.getDbView(viewId);
            List result = dbSearcher.search(view, request, view.getType());
            if (result != null) {
                EasyExcelUtils.exportExcel(resp, result, view.getType());
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            resp.getWriter().write(JsonUtils.toJsonStr(ApiResponse.failed(e.getMessage())));
        }
    }
}
